const STORAGE_PREFIX = 'USE_GLOBAL_STATE_';
const storageData = {};

/**
 * 对state进行格式化
 * @param {*} storage 
 */
function initStorageData(storage) {
  const { keys = [] } = storage || {};
  const now = new Date().getTime();
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    if (key.indexOf(STORAGE_PREFIX) === 0) {
      let result = my.getStorageSync({ key }) || {};
      let value = result.data;
      try {
        value = JSON.parse(value);
        if (!value.timeout || now - value.time < value.timeout) {
          let storageKey = key.substring(STORAGE_PREFIX.length);
          storageData[storageKey] = value.state;
        } else {
          my.removeStorageSync({
            key
          });
        }
      } catch (e) { }
    }
  }
}

//初始化一次
initStorageData(my.getStorageInfoSync());

//设置缓存位置，及过期时间
const defaultOptions = {
  storage: null, //local
  storageTimeout: 0
};

//获取全局数据
function getGlobalState(name) {
  return storageData[name];
}

function setGlobalState(name, state, options = {}) {
  storageData[name] = state;
  if (options.storage === 'local') {
    my.setStorageSync({
      key: STORAGE_PREFIX + name,
      data: JSON.stringify({
        state,
        timeout: options.storageTimeout,
        time: new Date().getTime(),
      })
    });
  }
}

export default (defaultState, key, options) => {
  if (typeof key === 'undefined' && typeof options === 'undefined') {
    key = defaultState;
    defaultState = undefined;
  } else if (typeof key === 'object' && typeof options === 'undefined') {
    options = key;
    key = defaultState;
    defaultState = undefined;
  }

  options = {
    ...defaultOptions,
    ...options,
  };

  const getState = () => {
    return getGlobalState(key);
  }

  // let state = getState();

  const setState = (newState) => {
    setGlobalState(key, newState, options);
    // state = newState;
  };

  return [getState, setState];
};
